<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="logo">
          <el-icon class="logo-icon" color="#409eff">
            <DataBoard />
          </el-icon>
          <h2>健康管理</h2>
        </div>
        <h3 class="title">健康管理系统</h3>
        <p class="subtitle">管理员登录</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        auto-complete="on"
        label-position="left"
      >
        <el-form-item prop="username">
          <el-input
            ref="usernameInput"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
            size="large"
            prefix-icon="User"
            :show-password="false"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            :key="passwordType"
            ref="passwordInput"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            auto-complete="on"
            size="large"
            prefix-icon="Lock"
            @keyup.enter="handleLogin"
          >
            <template #suffix>
              <span class="show-pwd" @click="showPwd">
                <el-icon>
                  <component :is="passwordType === 'password' ? 'View' : 'Hide'" />
                </el-icon>
              </span>
            </template>
          </el-input>
        </el-form-item>

        <el-button
          :loading="loading"
          type="primary"
          size="large"
          class="login-button"
          @click="handleLogin"
        >
          登录
        </el-button>

        <div class="login-switch">
          <span>普通用户登录？</span>
          <el-link type="primary" @click="switchToPhoneLogin">点击切换</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
  password: [{ required: true, trigger: 'blur', message: '请输入密码' }]
}

const passwordType = ref('password')
const loading = ref(false)
const loginFormRef = ref<FormInstance>()
const usernameInput = ref()
const passwordInput = ref()

const showPwd = () => {
  passwordType.value = passwordType.value === 'password' ? 'text' : 'password'
}

const handleLogin = async () => {
  console.log('点击登录按钮')
  
  // 使用表单验证而不是直接检查
  if (!loginFormRef.value) return
  
  try {
    // 验证表单
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    console.log('登录请求参数:', { 
      username: loginForm.username, 
      password: loginForm.password 
    })
    
    // 确保调用的是用户store中的login方法
    const result = await userStore.login(loginForm.username, loginForm.password)
    
    console.log('登录结果:', result)
    
    if (result && result.success) {
      ElMessage.success('登录成功')
      // 根据用户类型跳转到不同的页面
      if (userStore.isAdmin) {
        router.push('/app/users')
      } else {
        router.push('/app/profile')
      }
    } else {
      throw new Error(result?.message || '登录失败')
    }
  } catch (error: any) {
    console.error('登录错误:', error)
    // 更详细地显示错误信息
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('登录失败，请检查用户名和密码')
    }
  } finally {
    loading.value = false
  }
}

// 切换到普通用户登录
const switchToPhoneLogin = () => {
  router.push('/phone-login')
}

onMounted(() => {
  // 自动聚焦用户名输入框
  if (usernameInput.value) {
    usernameInput.value.focus()
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url('@/assets/login-bg.svg') no-repeat center center;
    background-size: cover;
    opacity: 0.1;
  }

  .login-box {
    width: 450px;
    max-width: 90%;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
    padding: 40px 30px;
    backdrop-filter: blur(10px);
    position: relative;
    z-index: 1;

    .login-header {
      text-align: center;
      margin-bottom: 30px;

      .logo {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        margin-bottom: 15px;

        .logo-icon {
          font-size: 32px;
        }

        h2 {
          margin: 0;
          font-size: 28px;
          font-weight: 600;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
      }

      .title {
        font-size: 22px;
        color: #333;
        margin: 0 0 10px 0;
        font-weight: 500;
      }

      .subtitle {
        font-size: 14px;
        color: #909399;
        margin: 0;
      }
    }

    .login-form {
      .el-form-item {
        margin-bottom: 25px;
      }

      :deep(.el-input__wrapper) {
        border-radius: 8px;
        padding: 2px 15px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08) !important;
        transition: box-shadow 0.3s ease;

        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12) !important;
        }

        &.is-focus {
          box-shadow: 0 4px 15px rgba(64, 158, 255, 0.3) !important;
        }
      }

      :deep(.el-input__prefix) {
        .el-icon {
          font-size: 18px;
          color: #909399;
        }
      }
    }

    .login-button {
      width: 100%;
      height: 48px;
      margin: 10px 0 25px;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 500;
      letter-spacing: 1px;
      background: linear-gradient(135deg, #409eff 0%, #667eea 100%);
      border: none;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(64, 158, 255, 0.4);
      }
    }

    .login-switch {
      text-align: center;
      margin-top: 20px;
      font-size: 14px;
      color: #909399;

      .el-link {
        margin-left: 5px;
        font-size: 14px;
      }
    }
  }

  .show-pwd {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 18px;
    color: #909399;
    cursor: pointer;
    user-select: none;
    transition: color 0.3s ease;

    &:hover {
      color: #409eff;
    }
  }
}

@media (max-width: 768px) {
  .login-container {
    padding: 20px;

    .login-box {
      padding: 30px 20px;
      width: 100%;

      .login-header {
        .logo {
          .logo-icon {
            font-size: 28px;
          }

          h2 {
            font-size: 24px;
          }
        }

        .title {
          font-size: 20px;
        }
      }
    }
  }
}
</style>
